using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using GameFramework.common;
using GameFramework.UI;
using UnityEngine;
using YamlDotNet.Serialization;
using YamlDotNet.Serialization.NamingConventions;

public class GameManager : MonoSingleton<GameManager>
{
    public Map map = new Map();
    //TODO 这些预制件由资源管理类进行管理
    public GameObject roadPrefab;
    public GameObject enimyPrefab;
    private Transform enimyRoot;
    public LevelData nowLevel;
    public Dictionary<int, LevelData> levelMap = new Dictionary<int, LevelData>();
    public List<LevelData> levels = new List<LevelData>();
    private GameObject bg;

    private int selectTowerId = -1;

    public int SelectTowerId
    {
        get => selectTowerId;
        set
        {

            if (value !=selectTowerId && selectTowerId!=-1)
            {
                
                EventManager.Instance.dispatch(new CancelSelectTowerEvent(selectTowerId));
            }
            selectTowerId = value;
        }
    }

    public bool selectedTower()
    {
        return SelectTowerId != -1;
    }
    public void cancelSelect()
    {
         SelectTowerId = -1;
    }
    // Start is called before the first frame update

    void Start()
    {
        //load 关卡数据
        loadLevelDatas();
        if (levels.Count == 0)
        {
            Debug.LogError("没有关卡数据，无法进行地图初始化！");
            return;
        }

        enimyRoot = GameObject.FindWithTag("EnimyRoot").transform;
        //初始化默认地图（上次没有挑战则用最小关）
        if (nowLevel == null)
        {
            nowLevel = levels[0];
        }

        //初始化第一关
        this.bg = GameObject.FindWithTag("Bg");
        for (int i = 0; i < 21; i++)
        {
            nowLevel.roads.Add(new Vector2(3, i));
        }

        // Debug.Log("路点数量："+nowLevel.roads.Count);
        DontDestroyOnLoad(this.gameObject);
        //TODO 初始化地图信息，即加载新的管卡时，需要做的事情
        // 1.MapCell初始化
        // 2.网格重新初始化
        // 3.根据路点重新生成路径
        this.map.roadPrefab = roadPrefab;
        this.map.initMapCell(nowLevel, () =>
        {
            //网格默认就显示？不显示这里就不初始化
            // GridScript gridScript = this.bg.GetComponent<GridScript>();
            // gridScript.initGrid(12,20);
        });
        
        //显示UI
        // UIManager.Instance.show<MainView>();
    }

    public void loadLevelDatas()
    {
        var deserializer = new DeserializerBuilder()
            .WithNamingConvention(CamelCaseNamingConvention.Instance)
            .Build();
        TextAsset[] textAssets = UnityEngine.Resources.LoadAll<TextAsset>("Levels");
        
        foreach (TextAsset asset in textAssets)
        {
            var assetText = asset.text;
            StringReader reader = new StringReader(assetText);
            var level = deserializer.Deserialize<LevelData>(reader);
            if (levelMap.ContainsKey(level.level))
            {
                Debug.LogError("重复的关卡数据："+level.level+" "+level.name);;
                continue;
            }
            
            levelMap.Add(level.level,level);
            levels.Add(level);
        }

        if (levels.Count >1)
        {
            levels.Sort((old,newV)=>
            {
                return newV.level - old.level;
            });
        }

    }

    public Vector2 getIndexByPos(Vector2 pos)
    {

        // int x = pos.x > 0 ? (int)Math.Ceiling(pos.x) : (int)Math.Floor(pos.x);
        int x = (int)Math.Floor(pos.x);
        // int y = pos.y > 0 ? (int)Math.Ceiling(pos.y) : (int)Math.Ceiling(pos.y);
        int y = (int)Math.Ceiling(pos.y) ;

        int col = this.map.colNum / 2 + x;
        int row = this.map.rowNum / 2 - y;
        return new Vector2(row, col);
    }
    
    public Vector2 getMapCellPos(Vector2 index)
    {

        return this.map.mapCells[(int)index.x, (int)index.y].pos;
    }
    public MapCell getMapCell(Vector2 index)
    {
        if ((int)index.x >= map.rowNum || (int)index.y>=map.colNum)
        {
            return null;
        }

        return this.map.mapCells[(int)index.x, (int)index.y];
    }

    public void chubing()
    {
        if (!map.canChuBing())
        {
            return;
        }
        map.chubing();
        //协程创建怪物
        StartCoroutine(generatorEnimy());
    }

    public IEnumerator generatorEnimy()
    {
        yield return new WaitForSeconds(nowLevel.deleyPerBoshu);
        for (int i = 0; i < nowLevel.enimyNumPerBoshu; i++)
        {
            GameObject enimy = GameObject.Instantiate(enimyPrefab, getMapCellPos(map.roads[0]), Quaternion.identity);
            enimy.transform.parent = enimyRoot;
            var enimyData = enimy.GetComponent<EnimyData>();
            enimyData.speed = 1;
            //TODO enimy挂在到管理节点，并放入对象池
            yield return new WaitForSeconds(nowLevel.generatorInterval);
        }
    }

    public Vector3 getMoveTarget(int roadIndex,out bool hadTarget)
    {
        if (roadIndex >= map.roads.Count)
        {
            hadTarget = false;
            return Vector3.zero;
        }
        hadTarget = true;
       return getMapCellPos(map.roads[roadIndex]);
    }
}
